import Toast from "../../miniprogram_npm/@vant/weapp/toast/toast";
const app = getApp()
import {
  ajaxGetUserListByTel,
  ajaxUpdateUserImage,
} from '../../api/my'
import {
  ajaxUserRechargeVip
} from "../../api/ordering";
Page({
  /**
   * 页面的初始数据
   */
  data: {
    //自定义导航高度
    customNavHeight: app.globalData.customNavInfo.navHeight,
    baseURL: app.globalData.config.baseURL,
    //用户信息
    userInfo: null,
    currentUser: {},
    // 当前会员卡索引
    currentSwiperIndex: 0
  },

  /**
   * 生命周期函数--监听页面加载
   */
  onLoad: async function (options) {
    if (app.globalData.userInfo) {
      Toast.loading({
        message: '正在加载',
        forbidClick: true,
        duration: 0
      });
    }
    //监听
    app.addWatchHandle({
      id: 'homePage',
      callBack: (e) => {
        this.updateUserInfo();
      }
    })

  },
  // 更新页面数据
  async updatePageData() {
    if (!app.globalData.userInfo) {
      this.setData({
        userInfo: {},
        currentSwiperIndex: 0,
      })
      return
    }
    ajaxGetUserListByTel({
      k1UserId: app.globalData.userInfo.k1UserId
    }).then(({
      data
    }) => {
      data.dataList.forEach(item => {
        if (!item.integral) {
          item.integral = 0
        }
        if (!item.points) {
          item.points = 0
        }
        if (!item.transcript) {
          item.transcript = 0
        }
        if (!item.transcript) {
          item.bestTime = '暂无'
        }
      })
      this.setData({
        userInfo: data,
        currentUser: data.dataList[this.data.currentSwiperIndex]
      })
      Toast.clear();
      app.myNextTick()
    }).catch(err => {
      Toast.clear();
      app.myNextTick()
      Toast(err.msg || '错误')
    })
  },
  // 滑动change
  swiperChange(e) {
    let current = e.detail.current;
    this.setData({
      currentSwiperIndex: current,
      currentUser: this.data.userInfo.dataList[current]
    })
  },
  // 更新用户信息
  updateUserInfo() {
    // 更新页面数据
    this.updatePageData();
  },
  // 去登录注册页面
  toLogin() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
  },
  // 去用户信息页面
  toUserInfo() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    const {
      k1UserId
    } = this.data.userInfo
    app.commonNavigateTo(`/pages/myInner/userDetails/index?k1UserId=${k1UserId}&isOut=true`)
  },
  // 获取用户信息
  getUserProfile() {
    if (!app.globalData.userInfo) {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return;
    }
    if (this.data.userInfo) {
      wx.getUserProfile({
        desc: '获取用户信息',
      }).then(res => {
        return ajaxUpdateUserImage({
          k1UserId: this.data.userInfo.k1UserId,
          imageUrl: res.userInfo.avatarUrl
        }).then(() => {
          this.updatePageData()
        })
      })
    } else {
      this.toLogin()
    }
  },
  swiperTap() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
  },
  // 查看会员卡二维码
  toQRCode() {
    if (!app.globalData.userInfo) {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return;
    }
    const current = this.data.userInfo.dataList[this.data.currentSwiperIndex]
    app.commonNavigateTo('/pages/myInner/vieCode/index?info=' + JSON.stringify(current))
  },
  // 前往点数记录
  toPointList() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    const {
      userInfo,
      currentSwiperIndex: index
    } = this.data
    const {
      points,
      k1UserId
    } = userInfo.dataList[index]
    app.commonNavigateTo(`/pages/myInner/point/index?points=${points}&k1UserId=${k1UserId}`)
  },
  // 前往积分记录
  toIntegralList() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    const {
      userInfo,
      currentSwiperIndex: index
    } = this.data
    const {
      integral,
      k1UserId
    } = userInfo.dataList[index]
    app.commonNavigateTo(`/pages/myInner/integral/index?integral=${integral}&k1UserId=${k1UserId}`)
  },
  // 前往成绩单列表
  toReportCard() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    const {
      userInfo,
      currentSwiperIndex: index
    } = this.data
    const {
      k1UserId,
      bestTime
    } = userInfo.dataList[index]
    app.commonNavigateTo(`/pages/myInner/ranking/index?k1UserId=${k1UserId}&bestTime=${bestTime||'暂无'}`)
  },
  // 购买年度会员
  async toPurchaseVip(e) {
    let {
      id
    } = e.currentTarget.dataset;
    // 没有选择店铺,去选择店铺，选择后自动跳转支付页面
    if (!app.globalData.shopInfo) {
      app.commonNavigateTo(`/pages/ordering/selectStore/index?userRechargeVipId=${id}`);
      return;
    }
    Toast.loading({
      message: '正在处理',
      forbidClick: true,
      duration: 0
    });
    try {
      let {
        data
      } = await ajaxUserRechargeVip({
        "buyDetailUserId": id,
        "orderSource": app.globalData.shopInfo.shopId,
        "productId": "10032"
      })
      app.storeModules.order.data.triggerRefresh = true;
      await app.myNextTick()
      Toast.clear();
      app.commonNavigateTo('/pages/ordering/orderPayment/index', {
        orderId: data.orderId
      })
    } catch (err) {
      await app.myNextTick()
      Toast.clear(err.msg || '错误');
    }
  },
  // 查看比赛安排
  toSchedule() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    const {
      tel,
      k1UserId
    } = this.data.userInfo
    app.commonNavigateTo(`/pages/myInner/matches/index?tel=${tel}&k1UserId=${k1UserId}`)
  },
  // 比赛实况
  toMatchLive() {
    app.commonNavigateTo('/pages/myInner/live/index')
  },
  // 查看所有会员
  toAllVip() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    const {
      k1UserId
    } = this.data.userInfo
    app.commonNavigateTo(`/pages/myInner/allVip/index?k1UserId=${k1UserId}`)
  },
  // 联系客服
  toContact() {
    app.commonNavigateTo('/pages/myInner/service/index')
  },
  // 填写预约
  goSubscribe() {
    if (JSON.stringify(this.data.userInfo) === '{}') {
      app.commonNavigateTo('/pages/registerLogin/home/index')
      return
    }
    app.commonNavigateTo('/pages/myInner/appointment/index')
  },
  // 待核销订单
  awaitWriteOffOrder() {
    app.commonNavigateTo('/pages/order/awaitWriteOffOrder/index')
  },
  // 扫描核销
  scanWriteOff() {
    wx.scanCode({
      // onlyFromCamera: true,
      scanType: ['qrCode'],
      success: (res) => {
        let result = res.result;
        if (result) {
          app.commonNavigateTo(`/pages/order/orderDetails/index?orderId=${result}&isWriteOffConfirm=${true}`)
        } else {
          Toast('扫码错误');
        }
      },
      fail: (err) => {
        Toast('扫码fail');
      }
    })
  },
  // 核销记录
  writeLog() {
    //前往核销记录页面
    app.commonNavigateTo(`/pages/order/writeOffRecord/index`)
  },
  // 退款申请
  goRefundApplication() {
    app.commonNavigateTo(`/pages/order/refundAudit/index`)
  },
  // 权限管理
  goUserPower() {
    app.commonNavigateTo(`/pages/permissionManage/index`)
  },

  showRank(){
    app.commonNavigateTo(`/pages/ranking/index`)
  },
  /**
   * 生命周期函数--监听页面初次渲染完成
   */
  onReady: function () {},

  /**
   * 生命周期函数--监听页面显示
   */
  onShow: function () {
    this.updateUserInfo();
  },

  /**
   * 生命周期函数--监听页面隐藏
   */
  onHide: function () {

  },

  /**
   * 生命周期函数--监听页面卸载
   */
  onUnload: function () {

  }
})